# import pygame
# import random
# import os
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
#
# # 卡片尺寸和间距
# CARD_WIDTH = 50
# CARD_HEIGHT = 60
# SPACING = 10
# # 叠罗汉偏移量
# OVERLAP_OFFSET = 5
#
# # 游戏区域布局
# GRID_ROWS = 6
# GRID_COLS = 6
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 道具按钮设置
# ITEM_WIDTH = 80
# ITEM_HEIGHT = 40
# ITEM_SPACING = 20
# ITEM_LEFT = (SCREEN_WIDTH - (2 * ITEM_WIDTH + ITEM_SPACING)) // 2
# ITEM_TOP = 20
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))  # 背景图宽度翻倍，用于移动
#     print("主背景图像加载成功")
#     bg_x = 0  # 背景图初始x坐标
#     BG_MOVE_SPEED = 1  # 背景图移动速度
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#     bg_x = 0
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(7):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#     ]
#
# # 游戏状态
# slots = []
# score = 0
# game_over = False
# game_won = False
# # 消去动画相关变量
# eliminate_animation = False
# eliminate_index = None
# animation_timer = 0
# ANIMATION_DURATION = 10
#
# # 道具数量
# remove_card_count = 3
# shuffle_count = 3
#
# # 卡片移动动画相关变量
# card_moving = False
# moving_card = None
# start_x = 0
# start_y = 0
# target_x = 0
# target_y = 0
# move_timer = 0
# MOVE_DURATION = 20
#
#
# def check_victory():
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
#
# def remove_card():
#     global remove_card_count
#     if remove_card_count > 0 and slots:
#         slots.pop()
#         remove_card_count -= 1
#
#
# def shuffle_grid():
#     global shuffle_count
#     if shuffle_count > 0:
#         all_cards = []
#         for row in grid:
#             for stack in row:
#                 all_cards.extend(stack)
#                 stack.clear()
#         random.shuffle(all_cards)
#         index = 0
#         for row in grid:
#             for stack in row:
#                 layers = random.randint(3, 5)
#                 stack.extend(all_cards[index:index + layers])
#                 index += layers
#         shuffle_count -= 1
#
#
# # 初始化卡片堆
# grid = []
# for row in range(GRID_ROWS):
#     grid_row = []
#     for col in range(GRID_COLS):
#         layers = random.randint(3, 5)
#         max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
#         stack = [random.randint(0, max_card_type) for _ in range(layers)]
#         stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
#         grid_row.append(stack)
#     grid.append(grid_row)
#
# # 主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
#             x, y = pygame.mouse.get_pos()
#             # 检查是否点击道具按钮
#             if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                 remove_card()
#             elif ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= x <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                 shuffle_grid()
#             else:
#                 # 计算点击位置
#                 grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#                 grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#                 # 检查点击范围
#                 if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                     if len(grid[grid_row][grid_col]) > 0:
#                         # 检查槽位是否已满（改为7块）
#                         if len(slots) >= SLOT_COLS:
#                             game_over = True
#                             continue
#
#                         # 取出顶层卡片
#                         moving_card = grid[grid_row][grid_col].pop()
#                         start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING)
#                         start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) + (len(grid[grid_row][grid_col])) * OVERLAP_OFFSET
#                         target_x = SLOT_LEFT + len(slots) * (CARD_WIDTH + 5)
#                         target_y = SLOT_TOP
#                         card_moving = True
#                         move_timer = 0
#
#     # 移动背景图
#     bg_x -= BG_MOVE_SPEED
#     if bg_x <= -SCREEN_WIDTH:
#         bg_x = 0
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (bg_x, 0))
#         screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))  # 绘制第二张背景图，实现无缝衔接
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制卡片堆，添加叠罗汉效果
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             stack = grid[row][col]
#             for i, card_type in enumerate(stack):
#                 offset_y = i * OVERLAP_OFFSET
#                 if card_images:
#                     screen.blit(card_images[card_type], (x, y + offset_y))
#                 else:
#                     pygame.draw.rect(screen, COLORS[card_type], (x, y + offset_y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(screen, (200, 200, 200),
#                          (SLOT_LEFT - 5, SLOT_TOP - 5,
#                           slot_width + 10, SLOT_HEIGHT + 10),
#                          border_radius=10)
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         if eliminate_animation and i >= eliminate_index and i < eliminate_index + 3:
#             alpha = 255 - (animation_timer * (255 // ANIMATION_DURATION))
#             if card_images:
#                 img = card_images[card].copy()
#                 img.set_alpha(alpha)
#                 screen.blit(img, (SLOT_LEFT + i * (CARD_WIDTH + 5), SLOT_TOP))
#             else:
#                 surface = pygame.Surface((CARD_WIDTH, CARD_HEIGHT))
#                 surface.set_alpha(alpha)
#                 surface.fill(COLORS[card])
#                 screen.blit(surface, (SLOT_LEFT + i * (CARD_WIDTH + 5), SLOT_TOP))
#         else:
#             x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             if card_images:
#                 screen.blit(card_images[card], (x, SLOT_TOP))
#             else:
#                 pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 处理卡片移动动画
#     if card_moving:
#         progress = move_timer / MOVE_DURATION
#         current_x = start_x + (target_x - start_x) * progress
#         current_y = start_y + (target_y - start_y) * progress
#         if card_images:
#             screen.blit(card_images[moving_card], (current_x, current_y))
#         else:
#             pygame.draw.rect(screen, COLORS[moving_card], (current_x, current_y, CARD_WIDTH, CARD_HEIGHT))
#         move_timer += 1
#         if move_timer >= MOVE_DURATION:
#             slots.append(moving_card)
#             card_moving = False
#             moving_card = None
#             # 检查连续三个相同卡片
#             if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                 eliminate_animation = True
#                 eliminate_index = len(slots) - 3
#                 score += 1
#
#             # 再次检查槽位是否已满
#             if len(slots) >= SLOT_COLS:
#                 game_over = True
#
#             # 检查胜利条件
#             if check_victory():
#                 game_won = True
#                 game_over = True
#
#     # 处理消去动画
#     if eliminate_animation:
#         animation_timer += 1
#         if animation_timer >= ANIMATION_DURATION:
#             del slots[eliminate_index:eliminate_index + 3]
#             eliminate_animation = False
#             animation_timer = 0
#             eliminate_index = None
#
#     # 绘制状态信息
#     font = pygame.font.Font(None, 36)
#     text = font.render(f"Score: {score}", True, (0, 0, 0))
#     screen.blit(text, (20, 20))
#
#     # 绘制槽位容量提示
#     capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
#     screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))
#
#     # 绘制道具按钮
#     pygame.draw.rect(screen, (0, 128, 0), (ITEM_LEFT, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT))
#     pygame.draw.rect(screen, (0, 0, 128), (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT))
#     font = pygame.font.Font(None, 24)
#     remove_text = font.render(f"移除: {remove_card_count}", True, (255, 255, 255))
#     shuffle_text = font.render(f"洗牌: {shuffle_count}", True, (255, 255, 255))
#     screen.blit(remove_text, (ITEM_LEFT + 10, ITEM_TOP + 10))
#     screen.blit(shuffle_text, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING + 10, ITEM_TOP + 10))
#
#     if game_over:
#         text = font.render("YOU WIN!" if game_won else "GAME OVER!",
#                            True, (0, 255, 0) if game_won else (255, 0, 0))
#         screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))
#
#     pygame.display.flip()
#     clock.tick(30)
#
# pygame.quit()


# import pygame
# import random
# import os
# import math
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
# TEXT_COLOR = (0, 0, 0)
# CAPACITY_COLOR = (100, 100, 100)
# ITEM_COLOR_1 = (0, 128, 0)
# ITEM_COLOR_2 = (0, 0, 128)
# ITEM_TEXT_COLOR = (255, 255, 255)
# WIN_COLOR = (0, 255, 0)
# LOSE_COLOR = (255, 0, 0)
#
# # 卡片尺寸和间距
# CARD_WIDTH = 50
# CARD_HEIGHT = 60
# SPACING = 10
# # 叠罗汉偏移量
# OVERLAP_OFFSET = 2
#
# # 游戏区域布局
# GRID_ROWS = 6
# GRID_COLS = 6
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 道具按钮设置
# ITEM_WIDTH = 80
# ITEM_HEIGHT = 40
# ITEM_SPACING = 20
# ITEM_LEFT = (SCREEN_WIDTH - (2 * ITEM_WIDTH + ITEM_SPACING)) // 2
# ITEM_TOP = 20
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))  # 背景图宽度翻倍，用于移动
#     print("主背景图像加载成功")
#     bg_x = 0  # 背景图初始x坐标
#     BG_MOVE_SPEED = 1  # 背景图移动速度
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#     bg_x = 0
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(7):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#     ]
#
#
# # 粒子效果类
# class Particle:
#     def __init__(self, x, y, color):
#         self.x = x
#         self.y = y
#         self.color = color
#         self.radius = random.randint(2, 5)
#         self.speed_x = random.uniform(-3, 3)
#         self.speed_y = random.uniform(-5, -1)
#         self.gravity = 0.1
#         self.life = random.randint(20, 40)
#
#     def update(self):
#         self.x += self.speed_x
#         self.y += self.speed_y
#         self.speed_y += self.gravity
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             s = pygame.Surface((self.radius * 2, self.radius * 2), pygame.SRCALPHA)
#             pygame.draw.circle(s, (*self.color, alpha), (self.radius, self.radius), self.radius)
#             surface.blit(s, (int(self.x - self.radius), int(self.y - self.radius)))
#
#
# # 得分增加动画类
# class ScorePopup:
#     def __init__(self, x, y):
#         self.x = x
#         self.y = y
#         self.value = "+1"
#         self.font = pygame.font.Font(None, 30)
#         self.color = (255, 215, 0)  # 金色
#         self.life = 40
#         self.speed_y = -1
#
#     def update(self):
#         self.y += self.speed_y
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             text = self.font.render(self.value, True, self.color)
#             text.set_alpha(alpha)
#             surface.blit(text, (self.x, self.y))
#
#
# # 游戏状态
# slots = []
# score = 0
# game_over = False
# game_won = False
# # 消去动画相关变量
# eliminate_animation = False
# eliminate_indices = []
# animation_timer = 0
# ANIMATION_DURATION = 30  # 延长动画时间，使效果更流畅
#
# # 粒子效果列表
# particles = []
# # 得分动画列表
# score_popups = []
#
# # 道具数量
# remove_card_count = 3
# shuffle_count = 3
#
# # 卡片移动动画相关变量
# card_moving = False
# moving_card = None
# start_x = 0
# start_y = 0
# target_x = 0
# target_y = 0
# move_timer = 0
# MOVE_DURATION = 20
#
#
# def check_victory():
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
#
# def remove_card():
#     global remove_card_count
#     if remove_card_count > 0 and slots:
#         slots.pop()
#         remove_card_count -= 1
#
#
# def shuffle_grid():
#     global shuffle_count
#     if shuffle_count > 0:
#         all_cards = []
#         for row in grid:
#             for stack in row:
#                 all_cards.extend(stack)
#                 stack.clear()
#         random.shuffle(all_cards)
#         index = 0
#         for row in grid:
#             for stack in row:
#                 layers = random.randint(3, 5)
#                 stack.extend(all_cards[index:index + layers])
#                 index += layers
#         shuffle_count -= 1
#
#
# # 初始化卡片堆
# grid = []
# for row in range(GRID_ROWS):
#     grid_row = []
#     for col in range(GRID_COLS):
#         layers = random.randint(3, 5)
#         max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
#         stack = [random.randint(0, max_card_type) for _ in range(layers)]
#         stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
#         grid_row.append(stack)
#     grid.append(grid_row)
#
# # 主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
#             x, y = pygame.mouse.get_pos()
#             # 检查是否点击道具按钮
#             if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                 remove_card()
#             elif ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= x <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                 shuffle_grid()
#             else:
#                 # 计算点击位置
#                 grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#                 grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#                 # 检查点击范围
#                 if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                     if len(grid[grid_row][grid_col]) > 0:
#                         # 检查槽位是否已满（改为7块）
#                         if len(slots) >= SLOT_COLS:
#                             game_over = True
#                             continue
#
#                         # 取出顶层卡片
#                         moving_card = grid[grid_row][grid_col].pop()
#                         start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING)
#                         start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) + (
#                             len(grid[grid_row][grid_col])) * OVERLAP_OFFSET
#                         target_x = SLOT_LEFT + len(slots) * (CARD_WIDTH + 5)
#                         target_y = SLOT_TOP
#                         card_moving = True
#                         move_timer = 0
#
#     # 移动背景图
#     bg_x -= BG_MOVE_SPEED
#     if bg_x <= -SCREEN_WIDTH:
#         bg_x = 0
#
#     # 更新粒子效果
#     for particle in particles[:]:
#         particle.update()
#         if particle.life <= 0:
#             particles.remove(particle)
#
#     # 更新得分动画
#     for popup in score_popups[:]:
#         popup.update()
#         if popup.life <= 0:
#             score_popups.remove(popup)
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (bg_x, 0))
#         screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))  # 绘制第二张背景图，实现无缝衔接
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制卡片堆，添加叠罗汉效果
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             stack = grid[row][col]
#             for i, card_type in enumerate(stack):
#                 offset_y = i * OVERLAP_OFFSET
#                 if card_images:
#                     screen.blit(card_images[card_type], (x, y + offset_y))
#                 else:
#                     pygame.draw.rect(screen, COLORS[card_type], (x, y + offset_y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(screen, (200, 200, 200),
#                          (SLOT_LEFT - 5, SLOT_TOP - 5,
#                           slot_width + 10, SLOT_HEIGHT + 10),
#                          border_radius=10)
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         if eliminate_animation and i in eliminate_indices:
#             # 计算动画进度 (0到1之间)
#             progress = animation_timer / ANIMATION_DURATION
#
#             # 计算卡片位置和大小
#             card_x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             card_y = SLOT_TOP
#
#             # 添加缩放效果
#             scale = 1 - progress
#             new_width = int(CARD_WIDTH * scale)
#             new_height = int(CARD_HEIGHT * scale)
#
#             # 居中显示缩放后的卡片
#             draw_x = card_x + (CARD_WIDTH - new_width) // 2
#             draw_y = card_y + (CARD_HEIGHT - new_height) // 2
#
#             # 透明度调整
#             alpha = int(255 * (1 - progress))
#
#             if card_images:
#                 # 创建卡片的临时副本并设置透明度
#                 img = card_images[card].copy()
#                 img = pygame.transform.scale(img, (new_width, new_height))
#                 img.set_alpha(alpha)
#                 screen.blit(img, (draw_x, draw_y))
#             else:
#                 surface = pygame.Surface((new_width, new_height), pygame.SRCALPHA)
#                 surface.fill((*COLORS[card], alpha))
#                 screen.blit(surface, (draw_x, draw_y))
#
#             # 在动画结束前创建粒子效果
#             if progress > 0.7:
#                 if random.random() < 0.3:  # 控制粒子生成频率
#                     color = COLORS[card] if not card_images else (255, 255, 255)
#                     for _ in range(3):
#                         particles.append(Particle(
#                             draw_x + new_width // 2,
#                             draw_y + new_height // 2,
#                             color
#                         ))
#         else:
#             x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             if card_images:
#                 screen.blit(card_images[card], (x, SLOT_TOP))
#             else:
#                 pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 处理卡片移动动画
#     if card_moving:
#         progress = move_timer / MOVE_DURATION
#         # 使用平滑的缓动函数替代线性插值
#         ease_progress = 0.5 - 0.5 * math.cos(progress * math.pi)
#         current_x = start_x + (target_x - start_x) * ease_progress
#         current_y = start_y + (target_y - start_y) * ease_progress
#         if card_images:
#             screen.blit(card_images[moving_card], (current_x, current_y))
#         else:
#             pygame.draw.rect(screen, COLORS[moving_card], (current_x, current_y, CARD_WIDTH, CARD_HEIGHT))
#         move_timer += 1
#         if move_timer >= MOVE_DURATION:
#             slots.append(moving_card)
#             card_moving = False
#             moving_card = None
#             # 检查连续三个相同卡片
#             if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                 eliminate_animation = True
#                 eliminate_indices = [len(slots) - 3, len(slots) - 2, len(slots) - 1]
#                 animation_timer = 0
#                 score += 1
#                 # 创建得分动画
#                 score_popups.append(ScorePopup(
#                     SLOT_LEFT + (len(slots) - 2) * (CARD_WIDTH + 5),
#                     SLOT_TOP - 30
#                 ))
#
#             # 再次检查槽位是否已满
#             if len(slots) >= SLOT_COLS:
#                 game_over = True
#
#             # 检查胜利条件
#             if check_victory():
#                 game_won = True
#                 game_over = True
#
#     # 处理消去动画
#     if eliminate_animation:
#         animation_timer += 1
#         if animation_timer >= ANIMATION_DURATION:
#             # 从后向前删除，避免索引变化问题
#             for i in sorted(eliminate_indices, reverse=True):
#                 del slots[i]
#             eliminate_animation = False
#             animation_timer = 0
#             eliminate_indices = []
#
#     # 绘制粒子效果
#     for particle in particles:
#         particle.draw(screen)
#
#     # 绘制得分动画
#     for popup in score_popups:
#         popup.draw(screen)
#
#     # 绘制状态信息
#     font = pygame.font.Font(None, 36)
#     text = font.render(f"Score: {score}", True, TEXT_COLOR)
#     screen.blit(text, (20, 20))
#
#     # 绘制槽位容量提示
#     capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, CAPACITY_COLOR)
#     screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))
#
#     # 绘制道具按钮
#     pygame.draw.rect(screen, ITEM_COLOR_1, (ITEM_LEFT, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT), border_radius=5)
#     pygame.draw.rect(screen, ITEM_COLOR_2, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
#                      border_radius=5)
#     font = pygame.font.Font(None, 24)
#     remove_text = font.render(f"移除: {remove_card_count}", True, ITEM_TEXT_COLOR)
#     shuffle_text = font.render(f"洗牌: {shuffle_count}", True, ITEM_TEXT_COLOR)
#     screen.blit(remove_text, (ITEM_LEFT + 10, ITEM_TOP + 10))
#     screen.blit(shuffle_text, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING + 10, ITEM_TOP + 10))
#
#     if game_over:
#         text = font.render("YOU WIN!" if game_won else "GAME OVER!",
#                            True, WIN_COLOR if game_won else LOSE_COLOR)
#         screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))
#
#     pygame.display.flip()
#     clock.tick(60)  # 提高帧率使动画更流畅
#
# pygame.quit()


# import pygame
# import random
# import os
# import math
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
# TEXT_COLOR = (0, 0, 0)
# CAPACITY_COLOR = (100, 100, 100)
# ITEM_COLOR_1 = (0, 128, 0)
# ITEM_COLOR_2 = (0, 0, 128)
# ITEM_TEXT_COLOR = (255, 255, 255)
# WIN_COLOR = (0, 255, 0)
# LOSE_COLOR = (255, 0, 0)
#
# # 卡片尺寸和间距
# CARD_WIDTH = 50
# CARD_HEIGHT = 60
# SPACING = 10
# # 叠罗汉偏移量
# OVERLAP_OFFSET = 2
#
# # 游戏区域布局
# GRID_ROWS = 6
# GRID_COLS = 6
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 道具按钮设置
# ITEM_WIDTH = 80
# ITEM_HEIGHT = 40
# ITEM_SPACING = 20
# ITEM_TOP = 20
# ITEM_LEFT = (SCREEN_WIDTH - (2 * ITEM_WIDTH + ITEM_SPACING)) // 2
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))
#     print("主背景图像加载成功")
#     bg_x = 0
#     BG_MOVE_SPEED = 1
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#     bg_x = 0
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(7):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#     ]
#
#
# # 粒子效果类
# class Particle:
#     def __init__(self, x, y, color):
#         self.x = x
#         self.y = y
#         self.color = color
#         self.radius = random.randint(2, 5)
#         self.speed_x = random.uniform(-3, 3)
#         self.speed_y = random.uniform(-5, -1)
#         self.gravity = 0.1
#         self.life = random.randint(20, 40)
#
#     def update(self):
#         self.x += self.speed_x
#         self.y += self.speed_y
#         self.speed_y += self.gravity
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             s = pygame.Surface((self.radius * 2, self.radius * 2), pygame.SRCALPHA)
#             pygame.draw.circle(s, (*self.color, alpha), (self.radius, self.radius), self.radius)
#             surface.blit(s, (int(self.x - self.radius), int(self.y - self.radius)))
#
#
# # 得分增加动画类
# class ScorePopup:
#     def __init__(self, x, y):
#         self.x = x
#         self.y = y
#         self.value = "+1"
#         self.font = pygame.font.Font(None, 30)
#         self.color = (255, 215, 0)  # 金色
#         self.life = 40
#         self.speed_y = -1
#
#     def update(self):
#         self.y += self.speed_y
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             text = self.font.render(self.value, True, self.color)
#             text.set_alpha(alpha)
#             surface.blit(text, (self.x, self.y))
#
#
# # 游戏状态
# slots = []
# score = 0
# game_over = False
# game_won = False
# # 消去动画相关变量
# eliminate_animation = False
# eliminate_indices = []
# animation_timer = 0
# ANIMATION_DURATION = 30
#
# # 粒子效果列表
# particles = []
# # 得分动画列表
# score_popups = []
#
# # 道具数量
# remove_card_count = 3
# shuffle_count = 3
#
# # 卡片移动动画相关变量
# card_moving = False
# moving_card = None
# start_x = 0
# start_y = 0
# target_x = 0
# target_y = 0
# move_timer = 0
# MOVE_DURATION = 20
#
#
# def check_victory(grid):
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
#
# def remove_card():
#     """移除槽位中最后一个卡片"""
#     global remove_card_count
#     if remove_card_count > 0 and slots:
#         slots.pop()
#         remove_card_count -= 1
#
#
# def shuffle_grid():
#     """洗牌功能"""
#     global shuffle_count
#     if shuffle_count > 0:
#         all_cards = []
#         for row in grid:
#             for stack in row:
#                 all_cards.extend(stack)
#                 stack.clear()
#         random.shuffle(all_cards)
#         index = 0
#         for row in grid:
#             for stack in row:
#                 layers = random.randint(3, 5)
#                 stack.extend(all_cards[index:index + layers])
#                 index += layers
#         shuffle_count -= 1
#
#
# # 初始化卡片堆
# grid = []
# for row in range(GRID_ROWS):
#     grid_row = []
#     for col in range(GRID_COLS):
#         layers = random.randint(3, 5)
#         max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
#         stack = [random.randint(0, max_card_type) for _ in range(layers)]
#         stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
#         grid_row.append(stack)
#     grid.append(grid_row)
#
# # 主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
#             x, y = pygame.mouse.get_pos()
#             # 检查是否点击道具按钮
#             if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                 remove_card()
#             elif ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= x <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                 shuffle_grid()
#             else:
#                 # 计算点击位置
#                 grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#                 grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#                 # 检查点击范围
#                 if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                     if len(grid[grid_row][grid_col]) > 0:
#                         # 检查槽位是否已满
#                         if len(slots) >= SLOT_COLS:
#                             game_over = True
#                             continue
#
#                         # 取出顶层卡片
#                         moving_card = grid[grid_row][grid_col].pop()
#                         start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING)
#                         start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) + (
#                             len(grid[grid_row][grid_col])) * OVERLAP_OFFSET
#                         target_x = SLOT_LEFT + len(slots) * (CARD_WIDTH + 5)
#                         target_y = SLOT_TOP
#                         card_moving = True
#                         move_timer = 0
#
#     # 移动背景图
#     bg_x -= BG_MOVE_SPEED
#     if bg_x <= -SCREEN_WIDTH:
#         bg_x = 0
#
#     # 更新粒子效果
#     for particle in particles[:]:
#         particle.update()
#         if particle.life <= 0:
#             particles.remove(particle)
#
#     # 更新得分动画
#     for popup in score_popups[:]:
#         popup.update()
#         if popup.life <= 0:
#             score_popups.remove(popup)
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (bg_x, 0))
#         screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制卡片堆，添加叠罗汉效果和鼠标悬停放大
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             stack = grid[row][col]
#             for i, card_type in enumerate(stack):
#                 offset_y = i * OVERLAP_OFFSET
#                 card_x = x
#                 card_y = y + offset_y
#
#                 # 检查鼠标是否悬停在卡片上
#                 mouse_x, mouse_y = pygame.mouse.get_pos()
#                 if (
#                         card_x <= mouse_x <= card_x + CARD_WIDTH
#                         and card_y <= mouse_y <= card_y + CARD_HEIGHT
#                 ):
#                     # 鼠标悬停，放大卡片
#                     scale_factor = 1.2
#                     scaled_width = int(CARD_WIDTH * scale_factor)
#                     scaled_height = int(CARD_HEIGHT * scale_factor)
#                     if card_images:
#                         scaled_img = pygame.transform.scale(card_images[card_type], (scaled_width, scaled_height))
#                         screen.blit(scaled_img, (
#                             card_x - (scaled_width - CARD_WIDTH) // 2,
#                             card_y - (scaled_height - CARD_HEIGHT) // 2
#                         ))
#                     else:
#                         pygame.draw.rect(
#                             screen,
#                             COLORS[card_type],
#                             (
#                                 card_x - (scaled_width - CARD_WIDTH) // 2,
#                                 card_y - (scaled_height - CARD_HEIGHT) // 2,
#                                 scaled_width,
#                                 scaled_height
#                             )
#                         )
#                 else:
#                     if card_images:
#                         screen.blit(card_images[card_type], (card_x, card_y))
#                     else:
#                         pygame.draw.rect(screen, COLORS[card_type], (card_x, card_y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(
#             screen,
#             (200, 200, 200),
#             (SLOT_LEFT - 5, SLOT_TOP - 5, slot_width + 10, SLOT_HEIGHT + 10),
#             border_radius=10
#         )
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         if eliminate_animation and i in eliminate_indices:
#             # 计算动画进度 (0到1之间)
#             progress = animation_timer / ANIMATION_DURATION
#
#             # 计算卡片位置和大小
#             card_x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             card_y = SLOT_TOP
#
#             # 添加缩放效果
#             scale = 1 - progress
#             new_width = int(CARD_WIDTH * scale)
#             new_height = int(CARD_HEIGHT * scale)
#
#             # 居中显示缩放后的卡片
#             draw_x = card_x + (CARD_WIDTH - new_width) // 2
#             draw_y = card_y + (CARD_HEIGHT - new_height) // 2
#
#             # 透明度调整
#             alpha = int(255 * (1 - progress))
#
#             if card_images:
#                 # 创建卡片的临时副本并设置透明度
#                 img = card_images[card].copy()
#                 img = pygame.transform.scale(img, (new_width, new_height))
#                 img.set_alpha(alpha)
#                 screen.blit(img, (draw_x, draw_y))
#             else:
#                 surface = pygame.Surface((new_width, new_height), pygame.SRCALPHA)
#                 surface.fill((*COLORS[card], alpha))
#                 screen.blit(surface, (draw_x, draw_y))
#
#             # 在动画结束前创建粒子效果
#             if progress > 0.7:
#                 if random.random() < 0.3:
#                     color = COLORS[card] if not card_images else (255, 255, 255)
#                     for _ in range(3):
#                         particles.append(Particle(
#                             draw_x + new_width // 2,
#                             draw_y + new_height // 2,
#                             color
#                         ))
#         else:
#             x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             if card_images:
#                 screen.blit(card_images[card], (x, SLOT_TOP))
#             else:
#                 pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 处理卡片移动动画
#     if card_moving:
#         progress = move_timer / MOVE_DURATION
#         # 使用平滑的缓动函数替代线性插值
#         ease_progress = 0.5 - 0.5 * math.cos(progress * math.pi)
#         current_x = start_x + (target_x - start_x) * ease_progress
#         current_y = start_y + (target_y - start_y) * ease_progress
#         if card_images:
#             screen.blit(card_images[moving_card], (current_x, current_y))
#         else:
#             pygame.draw.rect(screen, COLORS[moving_card], (current_x, current_y, CARD_WIDTH, CARD_HEIGHT))
#         move_timer += 1
#         if move_timer >= MOVE_DURATION:
#             slots.append(moving_card)
#             card_moving = False
#             moving_card = None
#             # 检查连续三个相同卡片
#             if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                 eliminate_animation = True
#                 eliminate_indices = [len(slots) - 3, len(slots) - 2, len(slots) - 1]
#                 animation_timer = 0
#                 score += 1
#                 # 创建得分动画
#                 score_popups.append(ScorePopup(
#                     SLOT_LEFT + (len(slots) - 2) * (CARD_WIDTH + 5),
#                     SLOT_TOP - 30
#                 ))
#
#             # 再次检查槽位是否已满
#             if len(slots) >= SLOT_COLS:
#                 game_over = True
#
#             # 检查胜利条件
#             if check_victory(grid):
#                 game_won = True
#                 game_over = True
#
#     # 处理消去动画
#     if eliminate_animation:
#         animation_timer += 1
#         if animation_timer >= ANIMATION_DURATION:
#             # 从后向前删除，避免索引变化问题
#             for i in sorted(eliminate_indices, reverse=True):
#                 del slots[i]
#             eliminate_animation = False
#             animation_timer = 0
#             eliminate_indices = []
#
#     # 绘制粒子效果
#     for particle in particles:
#         particle.draw(screen)
#
#     # 绘制得分动画
#     for popup in score_popups:
#         popup.draw(screen)
#
#     # 绘制状态信息
#     font = pygame.font.Font(None, 36)
#     text = font.render(f"Score: {score}", True, TEXT_COLOR)
#     screen.blit(text, (20, 20))
#
#     # 绘制槽位容量提示
#     capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, CAPACITY_COLOR)
#     screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))
#
#     # 绘制道具按钮
#     pygame.draw.rect(screen, ITEM_COLOR_1, (ITEM_LEFT, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT), border_radius=5)
#     pygame.draw.rect(screen, ITEM_COLOR_2, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
#                      border_radius=5)
#     font = pygame.font.Font(None, 24)
#     remove_text = font.render(f"移除: {remove_card_count}", True, ITEM_TEXT_COLOR)
#     shuffle_text = font.render(f"洗牌: {shuffle_count}", True, ITEM_TEXT_COLOR)
#     screen.blit(remove_text, (ITEM_LEFT + 10, ITEM_TOP + 10))
#     screen.blit(shuffle_text, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING + 10, ITEM_TOP + 10))
#
#     if game_over:
#         text = font.render("YOU WIN!" if game_won else "GAME OVER!",
#                            True, WIN_COLOR if game_won else LOSE_COLOR)
#         screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))
#
#     pygame.display.flip()
#     clock.tick(60)
#
# pygame.quit()


# import pygame
# import random
# import os
# import math
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
# TEXT_COLOR = (0, 0, 0)
# CAPACITY_COLOR = (100, 100, 100)
# ITEM_COLOR_1 = (0, 128, 0)
# ITEM_COLOR_2 = (0, 0, 128)
# ITEM_TEXT_COLOR = (255, 255, 255)
# WIN_COLOR = (0, 255, 0)
# LOSE_COLOR = (255, 0, 0)
# BUTTON_COLOR = (65, 105, 225)
# BUTTON_HOVER_COLOR = (70, 130, 180)
# BUTTON_TEXT_COLOR = (255, 255, 255)
#
# # 卡片尺寸和间距
# CARD_WIDTH = 50
# CARD_HEIGHT = 60
# SPACING = 10
# # 叠罗汉偏移量
# OVERLAP_OFFSET = 2
#
# # 游戏区域布局
# GRID_ROWS = 6
# GRID_COLS = 6
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 道具按钮设置
# ITEM_WIDTH = 80
# ITEM_HEIGHT = 40
# ITEM_SPACING = 20
# ITEM_TOP = 20
# ITEM_LEFT = (SCREEN_WIDTH - (2 * ITEM_WIDTH + ITEM_SPACING)) // 2
#
# # 重玩按钮设置
# RESTART_BUTTON_WIDTH = 150
# RESTART_BUTTON_HEIGHT = 50
# RESTART_BUTTON_LEFT = (SCREEN_WIDTH - RESTART_BUTTON_WIDTH) // 2
# RESTART_BUTTON_TOP = SCREEN_HEIGHT // 2 + 50
#
# # 动画常量
# ANIMATION_DURATION = 30  # 消去动画持续时间
# MOVE_DURATION = 20  # 卡片移动动画持续时间
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))
#     print("主背景图像加载成功")
#     bg_x = 0
#     BG_MOVE_SPEED = 1
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#     bg_x = 0
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(7):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#     ]
#
#
# # 粒子效果类
# class Particle:
#     def __init__(self, x, y, color):
#         self.x = x
#         self.y = y
#         self.color = color
#         self.radius = random.randint(2, 5)
#         self.speed_x = random.uniform(-3, 3)
#         self.speed_y = random.uniform(-5, -1)
#         self.gravity = 0.1
#         self.life = random.randint(20, 40)
#
#     def update(self):
#         self.x += self.speed_x
#         self.y += self.speed_y
#         self.speed_y += self.gravity
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             s = pygame.Surface((self.radius * 2, self.radius * 2), pygame.SRCALPHA)
#             pygame.draw.circle(s, (*self.color, alpha), (self.radius, self.radius), self.radius)
#             surface.blit(s, (int(self.x - self.radius), int(self.y - self.radius)))
#
#
# # 得分增加动画类
# class ScorePopup:
#     def __init__(self, x, y):
#         self.x = x
#         self.y = y
#         self.value = "+1"
#         self.font = pygame.font.Font(None, 30)
#         self.color = (255, 215, 0)  # 金色
#         self.life = 40
#         self.speed_y = -1
#
#     def update(self):
#         self.y += self.speed_y
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             text = self.font.render(self.value, True, self.color)
#             text.set_alpha(alpha)
#             surface.blit(text, (self.x, self.y))
#
#
# # 初始化游戏
# def init_game():
#     global slots, score, game_over, game_won, grid, remove_card_count, shuffle_count, particles, score_popups, eliminate_animation, eliminate_indices, animation_timer, card_moving, moving_card, start_x, start_y, target_x, target_y, move_timer
#     slots = []
#     score = 0
#     game_over = False
#     game_won = False
#     remove_card_count = 3
#     shuffle_count = 3
#     particles = []  # 初始化粒子效果列表
#     score_popups = []  # 初始化得分动画列表
#
#     # 消去动画相关变量
#     eliminate_animation = False
#     eliminate_indices = []
#     animation_timer = 0
#
#     # 卡片移动动画相关变量
#     card_moving = False
#     moving_card = None
#     start_x = 0
#     start_y = 0
#     target_x = 0
#     target_y = 0
#     move_timer = 0
#
#     # 初始化卡片堆
#     grid = []
#     for row in range(GRID_ROWS):
#         grid_row = []
#         for col in range(GRID_COLS):
#             layers = random.randint(3, 5)
#             max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
#             stack = [random.randint(0, max_card_type) for _ in range(layers)]
#             stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
#             grid_row.append(stack)
#         grid.append(grid_row)
#
#
# def check_victory(grid):
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
#
# def remove_card():
#     """移除槽位中最后一个卡片"""
#     global remove_card_count
#     if remove_card_count > 0 and slots:
#         slots.pop()
#         remove_card_count -= 1
#
#
# def shuffle_grid():
#     """洗牌功能"""
#     global shuffle_count
#     if shuffle_count > 0:
#         all_cards = []
#         for row in grid:
#             for stack in row:
#                 all_cards.extend(stack)
#                 stack.clear()
#         random.shuffle(all_cards)
#         index = 0
#         for row in grid:
#             for stack in row:
#                 layers = random.randint(3, 5)
#                 stack.extend(all_cards[index:index + layers])
#                 index += layers
#         shuffle_count -= 1
#
#
# # 初始化游戏
# init_game()
#
# # 游戏主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     mouse_pos = pygame.mouse.get_pos()
#     restart_button_hover = (
#             RESTART_BUTTON_LEFT <= mouse_pos[0] <= RESTART_BUTTON_LEFT + RESTART_BUTTON_WIDTH and
#             RESTART_BUTTON_TOP <= mouse_pos[1] <= RESTART_BUTTON_TOP + RESTART_BUTTON_HEIGHT
#     )
#
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN:
#             if game_over and restart_button_hover:
#                 init_game()
#             elif not game_over:
#                 x, y = event.pos
#                 # 检查是否点击道具按钮
#                 if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                     remove_card()
#                 elif ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= x <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                     shuffle_grid()
#                 else:
#                     # 计算点击位置
#                     grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#                     grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#                     # 检查点击范围
#                     if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                         if len(grid[grid_row][grid_col]) > 0:
#                             # 检查槽位是否已满
#                             if len(slots) >= SLOT_COLS:
#                                 game_over = True
#                                 continue
#
#                             # 取出顶层卡片
#                             moving_card = grid[grid_row][grid_col].pop()
#                             start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING)
#                             start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) + (
#                                 len(grid[grid_row][grid_col])) * OVERLAP_OFFSET
#                             target_x = SLOT_LEFT + len(slots) * (CARD_WIDTH + 5)
#                             target_y = SLOT_TOP
#                             card_moving = True
#                             move_timer = 0
#
#     # 移动背景图
#     bg_x -= BG_MOVE_SPEED
#     if bg_x <= -SCREEN_WIDTH:
#         bg_x = 0
#
#     # 更新粒子效果
#     for particle in particles[:]:
#         particle.update()
#         if particle.life <= 0:
#             particles.remove(particle)
#
#     # 更新得分动画
#     for popup in score_popups[:]:
#         popup.update()
#         if popup.life <= 0:
#             score_popups.remove(popup)
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (bg_x, 0))
#         screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制卡片堆，添加叠罗汉效果和鼠标悬停放大
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             stack = grid[row][col]
#             for i, card_type in enumerate(stack):
#                 offset_y = i * OVERLAP_OFFSET
#                 card_x = x
#                 card_y = y + offset_y
#
#                 # 检查鼠标是否悬停在卡片上
#                 mouse_x, mouse_y = pygame.mouse.get_pos()
#                 if (
#                         card_x <= mouse_x <= card_x + CARD_WIDTH
#                         and card_y <= mouse_y <= card_y + CARD_HEIGHT
#                 ):
#                     # 鼠标悬停，放大卡片
#                     scale_factor = 1.2
#                     scaled_width = int(CARD_WIDTH * scale_factor)
#                     scaled_height = int(CARD_HEIGHT * scale_factor)
#                     if card_images:
#                         scaled_img = pygame.transform.scale(card_images[card_type], (scaled_width, scaled_height))
#                         screen.blit(scaled_img, (
#                             card_x - (scaled_width - CARD_WIDTH) // 2,
#                             card_y - (scaled_height - CARD_HEIGHT) // 2
#                         ))
#                     else:
#                         pygame.draw.rect(
#                             screen,
#                             COLORS[card_type],
#                             (
#                                 card_x - (scaled_width - CARD_WIDTH) // 2,
#                                 card_y - (scaled_height - CARD_HEIGHT) // 2,
#                                 scaled_width,
#                                 scaled_height
#                             )
#                         )
#                 else:
#                     if card_images:
#                         screen.blit(card_images[card_type], (card_x, card_y))
#                     else:
#                         pygame.draw.rect(screen, COLORS[card_type], (card_x, card_y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(
#             screen,
#             (200, 200, 200),
#             (SLOT_LEFT - 5, SLOT_TOP - 5, slot_width + 10, SLOT_HEIGHT + 10),
#             border_radius=10
#         )
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         if eliminate_animation and i in eliminate_indices:
#             # 计算动画进度 (0到1之间)
#             progress = animation_timer / ANIMATION_DURATION
#
#             # 计算卡片位置和大小
#             card_x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             card_y = SLOT_TOP
#
#             # 添加缩放效果
#             scale = 1 - progress
#             new_width = int(CARD_WIDTH * scale)
#             new_height = int(CARD_HEIGHT * scale)
#
#             # 居中显示缩放后的卡片
#             draw_x = card_x + (CARD_WIDTH - new_width) // 2
#             draw_y = card_y + (CARD_HEIGHT - new_height) // 2
#
#             # 透明度调整
#             alpha = int(255 * (1 - progress))
#
#             if card_images:
#                 # 创建卡片的临时副本并设置透明度
#                 img = card_images[card].copy()
#                 img = pygame.transform.scale(img, (new_width, new_height))
#                 img.set_alpha(alpha)
#                 screen.blit(img, (draw_x, draw_y))
#             else:
#                 surface = pygame.Surface((new_width, new_height), pygame.SRCALPHA)
#                 surface.fill((*COLORS[card], alpha))
#                 screen.blit(surface, (draw_x, draw_y))
#
#             # 在动画结束前创建粒子效果
#             if progress > 0.7:
#                 if random.random() < 0.3:
#                     color = COLORS[card] if not card_images else (255, 255, 255)
#                     for _ in range(3):
#                         particles.append(Particle(
#                             draw_x + new_width // 2,
#                             draw_y + new_height // 2,
#                             color
#                         ))
#         else:
#             x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             if card_images:
#                 screen.blit(card_images[card], (x, SLOT_TOP))
#             else:
#                 pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 处理卡片移动动画
#     if card_moving:
#         progress = move_timer / MOVE_DURATION
#         # 使用平滑的缓动函数替代线性插值
#         ease_progress = 0.5 - 0.5 * math.cos(progress * math.pi)
#         current_x = start_x + (target_x - start_x) * ease_progress
#         current_y = start_y + (target_y - start_y) * ease_progress
#         if card_images:
#             screen.blit(card_images[moving_card], (current_x, current_y))
#         else:
#             pygame.draw.rect(screen, COLORS[moving_card], (current_x, current_y, CARD_WIDTH, CARD_HEIGHT))
#         move_timer += 1
#         if move_timer >= MOVE_DURATION:
#             slots.append(moving_card)
#             card_moving = False
#             moving_card = None
#             # 检查连续三个相同卡片
#             if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                 eliminate_animation = True
#                 eliminate_indices = [len(slots) - 3, len(slots) - 2, len(slots) - 1]
#                 animation_timer = 0
#                 score += 1
#                 # 创建得分动画
#                 score_popups.append(ScorePopup(
#                     SLOT_LEFT + (len(slots) - 2) * (CARD_WIDTH + 5),
#                     SLOT_TOP - 30
#                 ))
#
#             # 再次检查槽位是否已满
#             if len(slots) >= SLOT_COLS:
#                 game_over = True
#
#             # 检查胜利条件
#             if check_victory(grid):
#                 game_won = True
#                 game_over = True
#
#     # 处理消去动画
#     if eliminate_animation:
#         animation_timer += 1
#         if animation_timer >= ANIMATION_DURATION:
#             # 从后向前删除，避免索引变化问题
#             for i in sorted(eliminate_indices, reverse=True):
#                 del slots[i]
#             eliminate_animation = False
#             animation_timer = 0
#             eliminate_indices = []
#
#     # 绘制粒子效果
#     for particle in particles:
#         particle.draw(screen)
#
#     # 绘制得分动画
#     for popup in score_popups:
#         popup.draw(screen)
#
#     # 绘制状态信息
#     font = pygame.font.Font(None, 36)
#     text = font.render(f"Score: {score}", True, TEXT_COLOR)
#     screen.blit(text, (20, 20))
#
#     # 绘制槽位容量提示
#     capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, CAPACITY_COLOR)
#     screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))
#
#     # 绘制道具按钮
#     pygame.draw.rect(screen, ITEM_COLOR_1, (ITEM_LEFT, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT), border_radius=5)
#     pygame.draw.rect(screen, ITEM_COLOR_2, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
#                      border_radius=5)
#     font = pygame.font.Font(None, 24)
#     remove_text = font.render(f"移除: {remove_card_count}", True, ITEM_TEXT_COLOR)
#     shuffle_text = font.render(f"洗牌: {shuffle_count}", True, ITEM_TEXT_COLOR)
#     screen.blit(remove_text, (ITEM_LEFT + 10, ITEM_TOP + 10))
#     screen.blit(shuffle_text, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING + 10, ITEM_TOP + 10))
#
#     # 游戏结束时显示结果和重玩按钮
#     if game_over:
#         font = pygame.font.Font(None, 50)
#         text = font.render("YOU WIN!" if game_won else "GAME OVER!",
#                            True, WIN_COLOR if game_won else LOSE_COLOR)
#         screen.blit(text, (SCREEN_WIDTH // 2 - text.get_width() // 2, SCREEN_HEIGHT // 2 - 40))
#
#         # 绘制重玩按钮
#         button_color = BUTTON_HOVER_COLOR if restart_button_hover else BUTTON_COLOR
#         pygame.draw.rect(
#             screen,
#             button_color,
#             (RESTART_BUTTON_LEFT, RESTART_BUTTON_TOP, RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT),
#             border_radius=10
#         )
#         restart_text = font.render("再玩一次", True, BUTTON_TEXT_COLOR)
#         screen.blit(
#             restart_text,
#             (
#                 RESTART_BUTTON_LEFT + (RESTART_BUTTON_WIDTH - restart_text.get_width()) // 2,
#                 RESTART_BUTTON_TOP + (RESTART_BUTTON_HEIGHT - restart_text.get_height()) // 2
#             )
#         )
#
#     pygame.display.flip()
#     clock.tick(60)
#
# pygame.quit()

# import pygame
# import random
# import os
# import math
#
# # 初始化Pygame
# pygame.init()
#
# # 游戏窗口设置
# SCREEN_WIDTH = 480
# SCREEN_HEIGHT = 720
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("羊了个羊")
#
# # 颜色定义
# BG_COLOR = (255, 255, 255)
# TEXT_COLOR = (0, 0, 0)
# CAPACITY_COLOR = (100, 100, 100)
# ITEM_COLOR_1 = (0, 128, 0)  # 绿色 - 移除道具
# ITEM_COLOR_2 = (0, 0, 128)  # 蓝色 - 洗牌道具
# ITEM_TEXT_COLOR = (255, 255, 255)
# WIN_COLOR = (0, 128, 0)  # 深绿色 - 胜利文字
# LOSE_COLOR = (255, 0, 0)  # 红色 - 失败文字
# BUTTON_COLOR = (65, 105, 225)  # 皇家蓝 - 按钮背景
# BUTTON_HOVER_COLOR = (70, 130, 180)  # 钢蓝 - 按钮悬停
# BUTTON_TEXT_COLOR = (255, 255, 255)  # 白色 - 按钮文字
#
# # 卡片尺寸和间距
# CARD_WIDTH = 50
# CARD_HEIGHT = 60
# SPACING = 10
# # 叠罗汉偏移量
# OVERLAP_OFFSET = 2
#
# # 游戏区域布局
# GRID_ROWS = 6
# GRID_COLS = 6
# grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
# GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
# GRID_TOP = 100
#
# # 槽位区域设置
# SLOT_ROWS = 1
# SLOT_COLS = 7  # 最多存放7个卡片
# slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
# SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
# SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
# SLOT_HEIGHT = CARD_HEIGHT + 20
#
# # 道具按钮设置
# ITEM_WIDTH = 100  # 加宽按钮以适应中文
# ITEM_HEIGHT = 40
# ITEM_SPACING = 20
# ITEM_TOP = 20
# ITEM_LEFT = (SCREEN_WIDTH - (2 * ITEM_WIDTH + ITEM_SPACING)) // 2
#
# # 重玩按钮设置
# RESTART_BUTTON_WIDTH = 150
# RESTART_BUTTON_HEIGHT = 50
# RESTART_BUTTON_LEFT = (SCREEN_WIDTH - RESTART_BUTTON_WIDTH) // 2
# RESTART_BUTTON_TOP = SCREEN_HEIGHT // 2 + 50
#
# # 动画常量
# ANIMATION_DURATION = 30  # 消去动画持续时间
# MOVE_DURATION = 20  # 卡片移动动画持续时间
#
# # 加载背景图像
# try:
#     image_folder = os.path.join(os.path.dirname(__file__), "image")
#     background_path = os.path.join(image_folder, "back.png")
#     background_img = pygame.image.load(background_path)
#     background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))
#     print("主背景图像加载成功")
#     bg_x = 0
#     BG_MOVE_SPEED = 1
# except Exception as e:
#     print(f"主背景图像加载失败: {e}")
#     background_img = None
#     bg_x = 0
#
# # 加载槽位背景图像
# try:
#     slot_bg_path = os.path.join(image_folder, "back2.png")
#     slot_bg_img = pygame.image.load(slot_bg_path)
#     slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
#     print("槽位背景图像加载成功")
# except Exception as e:
#     print(f"槽位背景图像加载失败: {e}")
#     slot_bg_img = None
#
# # 加载卡片图片
# card_images = []
# try:
#     for i in range(7):
#         if i == 0:
#             tile_path = os.path.join(image_folder, "tile.png")
#         else:
#             tile_path = os.path.join(image_folder, f"tile{i}.png")
#
#         if os.path.exists(tile_path):
#             img = pygame.image.load(tile_path)
#             img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
#             card_images.append(img)
#             print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
#         else:
#             print(f"卡片图片 {tile_path} 不存在")
#
#     if not card_images:
#         raise Exception("没有找到任何卡片图片")
#
# except Exception as e:
#     print(f"卡片图片加载失败: {e}")
#     COLORS = [
#         (255, 0, 0),  # 红
#         (0, 255, 0),  # 绿
#         (0, 0, 255),  # 蓝
#         (255, 255, 0),  # 黄
#         (128, 0, 128),  # 紫
#         (255, 165, 0),  # 橙
#         (0, 191, 255),  # 天蓝
#     ]
#
# # 尝试加载中文字体
# try:
#     # 尝试加载系统中文字体
#     pygame.font.init()
#     font_options = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC", "Microsoft YaHei"]
#     font_available = None
#
#     for font_name in font_options:
#         if font_name in pygame.font.get_fonts():
#             font_available = font_name
#             break
#
#     if font_available:
#         print(f"找到中文字体: {font_available}")
#     else:
#         print("未找到系统中文字体，使用默认字体")
#         font_available = pygame.font.get_default_font()
#
# except Exception as e:
#     print(f"字体初始化失败: {e}")
#     font_available = pygame.font.get_default_font()
#
#
# # 粒子效果类
# class Particle:
#     def __init__(self, x, y, color):
#         self.x = x
#         self.y = y
#         self.color = color
#         self.radius = random.randint(2, 5)
#         self.speed_x = random.uniform(-3, 3)
#         self.speed_y = random.uniform(-5, -1)
#         self.gravity = 0.1
#         self.life = random.randint(20, 40)
#
#     def update(self):
#         self.x += self.speed_x
#         self.y += self.speed_y
#         self.speed_y += self.gravity
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             s = pygame.Surface((self.radius * 2, self.radius * 2), pygame.SRCALPHA)
#             pygame.draw.circle(s, (*self.color, alpha), (self.radius, self.radius), self.radius)
#             surface.blit(s, (int(self.x - self.radius), int(self.y - self.radius)))
#
#
# # 得分增加动画类
# class ScorePopup:
#     def __init__(self, x, y):
#         self.x = x
#         self.y = y
#         self.value = "+1"
#         self.font = pygame.font.SysFont(font_available, 30)
#         self.color = (255, 215, 0)  # 金色
#         self.life = 40
#         self.speed_y = -1
#
#     def update(self):
#         self.y += self.speed_y
#         self.life -= 1
#
#     def draw(self, surface):
#         alpha = int((self.life / 40) * 255)
#         if alpha > 0:
#             text = self.font.render(self.value, True, self.color)
#             text.set_alpha(alpha)
#             surface.blit(text, (self.x, self.y))
#
#
# # 初始化游戏
# def init_game():
#     global slots, score, game_over, game_won, grid, remove_card_count, shuffle_count, particles, score_popups, eliminate_animation, eliminate_indices, animation_timer, card_moving, moving_card, start_x, start_y, target_x, target_y, move_timer
#     slots = []
#     score = 0
#     game_over = False
#     game_won = False
#     remove_card_count = 3
#     shuffle_count = 3
#     particles = []  # 初始化粒子效果列表
#     score_popups = []  # 初始化得分动画列表
#
#     # 消去动画相关变量
#     eliminate_animation = False
#     eliminate_indices = []
#     animation_timer = 0
#
#     # 卡片移动动画相关变量
#     card_moving = False
#     moving_card = None
#     start_x = 0
#     start_y = 0
#     target_x = 0
#     target_y = 0
#     move_timer = 0
#
#     # 初始化卡片堆
#     grid = []
#     for row in range(GRID_ROWS):
#         grid_row = []
#         for col in range(GRID_COLS):
#             layers = random.randint(3, 5)
#             max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
#             stack = [random.randint(0, max_card_type) for _ in range(layers)]
#             stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
#             grid_row.append(stack)
#         grid.append(grid_row)
#
#
# def check_victory(grid):
#     """检查是否胜利"""
#     for row in grid:
#         for stack in row:
#             if len(stack) > 0:
#                 return False
#     return len(slots) == 0
#
#
# def remove_card():
#     """移除槽位中最后一个卡片"""
#     global remove_card_count
#     if remove_card_count > 0 and slots:
#         slots.pop()
#         remove_card_count -= 1
#
#
# def shuffle_grid():
#     """洗牌功能"""
#     global shuffle_count
#     if shuffle_count > 0:
#         all_cards = []
#         for row in grid:
#             for stack in row:
#                 all_cards.extend(stack)
#                 stack.clear()
#         random.shuffle(all_cards)
#         index = 0
#         for row in grid:
#             for stack in row:
#                 layers = random.randint(3, 5)
#                 stack.extend(all_cards[index:index + layers])
#                 index += layers
#         shuffle_count -= 1
#
#
# # 初始化游戏
# init_game()
#
# # 游戏主循环
# clock = pygame.time.Clock()
# running = True
#
# while running:
#     # 事件处理
#     mouse_pos = pygame.mouse.get_pos()
#     restart_button_hover = (
#             RESTART_BUTTON_LEFT <= mouse_pos[0] <= RESTART_BUTTON_LEFT + RESTART_BUTTON_WIDTH and
#             RESTART_BUTTON_TOP <= mouse_pos[1] <= RESTART_BUTTON_TOP + RESTART_BUTTON_HEIGHT
#     )
#
#     item1_button_hover = (
#             ITEM_LEFT <= mouse_pos[0] <= ITEM_LEFT + ITEM_WIDTH and
#             ITEM_TOP <= mouse_pos[1] <= ITEM_TOP + ITEM_HEIGHT
#     )
#
#     item2_button_hover = (
#             ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= mouse_pos[0] <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and
#             ITEM_TOP <= mouse_pos[1] <= ITEM_TOP + ITEM_HEIGHT
#     )
#
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == pygame.MOUSEBUTTONDOWN:
#             if game_over and restart_button_hover:
#                 init_game()
#             elif not game_over:
#                 x, y = event.pos
#                 # 检查是否点击道具按钮
#                 if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                     remove_card()
#                 elif ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= x <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
#                     shuffle_grid()
#                 else:
#                     # 计算点击位置
#                     grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
#                     grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
#                     # 检查点击范围
#                     if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
#                         if len(grid[grid_row][grid_col]) > 0:
#                             # 检查槽位是否已满
#                             if len(slots) >= SLOT_COLS:
#                                 game_over = True
#                                 continue
#
#                             # 取出顶层卡片
#                             moving_card = grid[grid_row][grid_col].pop()
#                             start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING)
#                             start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) + (
#                                 len(grid[grid_row][grid_col])) * OVERLAP_OFFSET
#                             target_x = SLOT_LEFT + len(slots) * (CARD_WIDTH + 5)
#                             target_y = SLOT_TOP
#                             card_moving = True
#                             move_timer = 0
#
#     # 移动背景图
#     bg_x -= BG_MOVE_SPEED
#     if bg_x <= -SCREEN_WIDTH:
#         bg_x = 0
#
#     # 更新粒子效果
#     for particle in particles[:]:
#         particle.update()
#         if particle.life <= 0:
#             particles.remove(particle)
#
#     # 更新得分动画
#     for popup in score_popups[:]:
#         popup.update()
#         if popup.life <= 0:
#             score_popups.remove(popup)
#
#     # 绘制界面
#     if background_img:
#         screen.blit(background_img, (bg_x, 0))
#         screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))
#     else:
#         screen.fill(BG_COLOR)
#
#     # 绘制标题
#     title_font = pygame.font.SysFont(font_available, 40)
#     title_text = title_font.render("羊了个羊", True, (0, 0, 0))
#     screen.blit(title_text, (SCREEN_WIDTH // 2 - title_text.get_width() // 2, 50))
#
#     # 绘制卡片堆，添加叠罗汉效果和鼠标悬停放大
#     for row in range(GRID_ROWS):
#         for col in range(GRID_COLS):
#             x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
#             y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
#             stack = grid[row][col]
#             for i, card_type in enumerate(stack):
#                 offset_y = i * OVERLAP_OFFSET
#                 card_x = x
#                 card_y = y + offset_y
#
#                 # 检查鼠标是否悬停在卡片上
#                 mouse_x, mouse_y = pygame.mouse.get_pos()
#                 if (
#                         card_x <= mouse_x <= card_x + CARD_WIDTH
#                         and card_y <= mouse_y <= card_y + CARD_HEIGHT
#                 ):
#                     # 鼠标悬停，放大卡片
#                     scale_factor = 1.2
#                     scaled_width = int(CARD_WIDTH * scale_factor)
#                     scaled_height = int(CARD_HEIGHT * scale_factor)
#                     if card_images:
#                         scaled_img = pygame.transform.scale(card_images[card_type], (scaled_width, scaled_height))
#                         screen.blit(scaled_img, (
#                             card_x - (scaled_width - CARD_WIDTH) // 2,
#                             card_y - (scaled_height - CARD_HEIGHT) // 2
#                         ))
#                     else:
#                         pygame.draw.rect(
#                             screen,
#                             COLORS[card_type],
#                             (
#                                 card_x - (scaled_width - CARD_WIDTH) // 2,
#                                 card_y - (scaled_height - CARD_HEIGHT) // 2,
#                                 scaled_width,
#                                 scaled_height
#                             )
#                         )
#                 else:
#                     if card_images:
#                         screen.blit(card_images[card_type], (card_x, card_y))
#                     else:
#                         pygame.draw.rect(screen, COLORS[card_type], (card_x, card_y, CARD_WIDTH, CARD_HEIGHT))
#
#     # 绘制槽位背景
#     if slot_bg_img:
#         screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
#     else:
#         pygame.draw.rect(
#             screen,
#             (200, 200, 200),
#             (SLOT_LEFT - 5, SLOT_TOP - 5, slot_width + 10, SLOT_HEIGHT + 10),
#             border_radius=10
#         )
#
#     # 绘制槽位标题
#     slot_font = pygame.font.SysFont(font_available, 24)
#     slot_text = slot_font.render("卡槽", True, (0, 0, 0))
#     screen.blit(slot_text, (SLOT_LEFT + slot_width // 2 - slot_text.get_width() // 2, SLOT_TOP - 30))
#
#     # 绘制槽位中的卡片
#     for i, card in enumerate(slots):
#         if eliminate_animation and i in eliminate_indices:
#             # 计算动画进度 (0到1之间)
#             progress = animation_timer / ANIMATION_DURATION
#
#             # 计算卡片位置和大小
#             card_x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             card_y = SLOT_TOP
#
#             # 添加缩放效果
#             scale = 1 - progress
#             new_width = int(CARD_WIDTH * scale)
#             new_height = int(CARD_HEIGHT * scale)
#
#             # 居中显示缩放后的卡片
#             draw_x = card_x + (CARD_WIDTH - new_width) // 2
#             draw_y = card_y + (CARD_HEIGHT - new_height) // 2
#
#             # 透明度调整
#             alpha = int(255 * (1 - progress))
#
#             if card_images:
#                 # 创建卡片的临时副本并设置透明度
#                 img = card_images[card].copy()
#                 img = pygame.transform.scale(img, (new_width, new_height))
#                 img.set_alpha(alpha)
#                 screen.blit(img, (draw_x, draw_y))
#             else:
#                 surface = pygame.Surface((new_width, new_height), pygame.SRCALPHA)
#                 surface.fill((*COLORS[card], alpha))
#                 screen.blit(surface, (draw_x, draw_y))
#
#             # 在动画结束前创建粒子效果
#             if progress > 0.7:
#                 if random.random() < 0.3:
#                     color = COLORS[card] if not card_images else (255, 255, 255)
#                     for _ in range(3):
#                         particles.append(Particle(
#                             draw_x + new_width // 2,
#                             draw_y + new_height // 2,
#                             color
#                         ))
#         else:
#             x = SLOT_LEFT + i * (CARD_WIDTH + 5)
#             if card_images:
#                 screen.blit(card_images[card], (x, SLOT_TOP))
#             else:
#                 pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))
#
#     # 处理卡片移动动画
#     if card_moving:
#         progress = move_timer / MOVE_DURATION
#         # 使用平滑的缓动函数替代线性插值
#         ease_progress = 0.5 - 0.5 * math.cos(progress * math.pi)
#         current_x = start_x + (target_x - start_x) * ease_progress
#         current_y = start_y + (target_y - start_y) * ease_progress
#         if card_images:
#             screen.blit(card_images[moving_card], (current_x, current_y))
#         else:
#             pygame.draw.rect(screen, COLORS[moving_card], (current_x, current_y, CARD_WIDTH, CARD_HEIGHT))
#         move_timer += 1
#         if move_timer >= MOVE_DURATION:
#             slots.append(moving_card)
#             card_moving = False
#             moving_card = None
#             # 检查连续三个相同卡片
#             if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
#                 eliminate_animation = True
#                 eliminate_indices = [len(slots) - 3, len(slots) - 2, len(slots) - 1]
#                 animation_timer = 0
#                 score += 1
#                 # 创建得分动画
#                 score_popups.append(ScorePopup(
#                     SLOT_LEFT + (len(slots) - 2) * (CARD_WIDTH + 5),
#                     SLOT_TOP - 30
#                 ))
#
#             # 再次检查槽位是否已满
#             if len(slots) >= SLOT_COLS:
#                 game_over = True
#
#             # 检查胜利条件
#             if check_victory(grid):
#                 game_won = True
#                 game_over = True
#
#     # 处理消去动画
#     if eliminate_animation:
#         animation_timer += 1
#         if animation_timer >= ANIMATION_DURATION:
#             # 从后向前删除，避免索引变化问题
#             for i in sorted(eliminate_indices, reverse=True):
#                 del slots[i]
#             eliminate_animation = False
#             animation_timer = 0
#             eliminate_indices = []
#
#     # 绘制粒子效果
#     for particle in particles:
#         particle.draw(screen)
#
#     # 绘制得分动画
#     for popup in score_popups:
#         popup.draw(screen)
#
#     # 绘制状态信息
#     status_font = pygame.font.SysFont(font_available, 28)
#     score_text = status_font.render(f"得分: {score}", True, TEXT_COLOR)
#     screen.blit(score_text, (20, 20))
#
#     # 绘制槽位容量提示
#     capacity_text = status_font.render(f"已用: {len(slots)}/{SLOT_COLS}", True, CAPACITY_COLOR)
#     screen.blit(capacity_text, (SCREEN_WIDTH - capacity_text.get_width() - 20, 20))
#
#     # 绘制道具按钮
#     # 移除道具按钮
#     pygame.draw.rect(
#         screen,
#         ITEM_COLOR_1 if not item1_button_hover else (0, 168, 0),
#         (ITEM_LEFT, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
#         border_radius=5
#     )
#     # 洗牌道具按钮
#     pygame.draw.rect(
#         screen,
#         ITEM_COLOR_2 if not item2_button_hover else (0, 0, 168),
#         (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
#         border_radius=5
#     )
#
#     # 绘制道具按钮文字
#     item_font = pygame.font.SysFont(font_available, 24)
#     remove_text = item_font.render(f"移除 ×{remove_card_count}", True, ITEM_TEXT_COLOR)
#     shuffle_text = item_font.render(f"洗牌 ×{shuffle_count}", True, ITEM_TEXT_COLOR)
#     screen.blit(remove_text, (ITEM_LEFT + 10, ITEM_TOP + 8))
#     screen.blit(shuffle_text, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING + 10, ITEM_TOP + 8))
#
#     # 游戏结束时显示结果和重玩按钮
#     if game_over:
#         # 绘制半透明遮罩
#         overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
#         overlay.fill((0, 0, 0, 128))
#         screen.blit(overlay, (0, 0))
#
#         # 绘制游戏结果
#         result_font = pygame.font.SysFont(font_available, 50)
#         result_text = result_font.render("恭喜你赢了!" if game_won else "游戏结束!",
#                                          True, WIN_COLOR if game_won else LOSE_COLOR)
#         screen.blit(result_text, (SCREEN_WIDTH // 2 - result_text.get_width() // 2, SCREEN_HEIGHT // 2 - 70))
#
#         # 绘制最终得分
#         final_score_font = pygame.font.SysFont(font_available, 36)
#         final_score_text = final_score_font.render(f"最终得分: {score}", True, (255, 255, 255))
#         screen.blit(final_score_text, (SCREEN_WIDTH // 2 - final_score_text.get_width() // 2, SCREEN_HEIGHT // 2 - 20))
#
#         # 绘制重玩按钮
#         pygame.draw.rect(
#             screen,
#             BUTTON_HOVER_COLOR if restart_button_hover else BUTTON_COLOR,
#             (RESTART_BUTTON_LEFT, RESTART_BUTTON_TOP, RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT),
#             border_radius=10
#         )
#         restart_text = pygame.font.SysFont(font_available, 36).render("再玩一次", True, BUTTON_TEXT_COLOR)
#         screen.blit(
#             restart_text,
#             (
#                 RESTART_BUTTON_LEFT + (RESTART_BUTTON_WIDTH - restart_text.get_width()) // 2,
#                 RESTART_BUTTON_TOP + (RESTART_BUTTON_HEIGHT - restart_text.get_height()) // 2
#             )
#         )
#
#     pygame.display.flip()
#     clock.tick(60)
#
# pygame.quit()


import pygame
import random
import os
import math
import time

# 初始化Pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 720
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("羊了个羊")

# 颜色定义
BG_COLOR = (255, 255, 255)
TEXT_COLOR = (0, 0, 0)
CAPACITY_COLOR = (100, 100, 100)
ITEM_COLOR_1 = (0, 128, 0)  # 绿色 - 移除道具
ITEM_COLOR_2 = (0, 0, 128)  # 蓝色 - 洗牌道具
ITEM_COLOR_3 = (128, 0, 0)  # 红色 - 提示道具
ITEM_TEXT_COLOR = (255, 255, 255)
WIN_COLOR = (0, 128, 0)  # 深绿色 - 胜利文字
LOSE_COLOR = (255, 0, 0)  # 红色 - 失败文字
BUTTON_COLOR = (65, 105, 225)  # 皇家蓝 - 按钮背景
BUTTON_HOVER_COLOR = (70, 130, 180)  # 钢蓝 - 按钮悬停
BUTTON_TEXT_COLOR = (255, 255, 255)  # 白色 - 按钮文字
HINT_COLOR = (255, 215, 0)  # 金色 - 提示高亮
TIME_BAR_COLOR = (255, 69, 0)  # 橙红色 - 时间条

# 卡片尺寸和间距
CARD_WIDTH = 50
CARD_HEIGHT = 60
SPACING = 10
# 叠罗汉偏移量
OVERLAP_OFFSET = 2

# 游戏区域布局
GRID_ROWS = 6
GRID_COLS = 6
grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
GRID_TOP = 100

# 槽位区域设置
SLOT_ROWS = 1
SLOT_COLS = 7  # 最多存放7个卡片
slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
SLOT_HEIGHT = CARD_HEIGHT + 20

# 道具按钮设置
ITEM_WIDTH = 80  # 调整按钮宽度
ITEM_HEIGHT = 40
ITEM_SPACING = 10
ITEM_TOP = 20
ITEM_LEFT = (SCREEN_WIDTH - (3 * ITEM_WIDTH + 2 * ITEM_SPACING)) // 2

# 重玩按钮设置
RESTART_BUTTON_WIDTH = 150
RESTART_BUTTON_HEIGHT = 50
RESTART_BUTTON_LEFT = (SCREEN_WIDTH - RESTART_BUTTON_WIDTH) // 2
RESTART_BUTTON_TOP = SCREEN_HEIGHT // 2 + 50

# 时间条设置
TIME_BAR_WIDTH = 200
TIME_BAR_HEIGHT = 15
TIME_BAR_LEFT = (SCREEN_WIDTH - TIME_BAR_WIDTH) // 2
TIME_BAR_TOP = 70

# 动画常量
ANIMATION_DURATION = 30  # 消去动画持续时间
MOVE_DURATION = 20  # 卡片移动动画持续时间
HINT_DURATION = 120  # 提示高亮持续时间

# 游戏难度设置
TIME_LIMIT = 300  # 时间限制（秒）
HARD_MODE_THRESHOLD = 20  # 难度提升阈值（分数）

# 加载背景图像
try:
    image_folder = os.path.join(os.path.dirname(__file__), "image")
    background_path = os.path.join(image_folder, "back.png")
    background_img = pygame.image.load(background_path)
    background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH * 2, SCREEN_HEIGHT))
    print("主背景图像加载成功")
    bg_x = 0
    BG_MOVE_SPEED = 1
except Exception as e:
    print(f"主背景图像加载失败: {e}")
    background_img = None
    bg_x = 0

# 加载槽位背景图像
try:
    slot_bg_path = os.path.join(image_folder, "back2.png")
    slot_bg_img = pygame.image.load(slot_bg_path)
    slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
    print("槽位背景图像加载成功")
except Exception as e:
    print(f"槽位背景图像加载失败: {e}")
    slot_bg_img = None

# 加载卡片图片
card_images = []
try:
    for i in range(7):
        if i == 0:
            tile_path = os.path.join(image_folder, "tile.png")
        else:
            tile_path = os.path.join(image_folder, f"tile{i}.png")

        if os.path.exists(tile_path):
            img = pygame.image.load(tile_path)
            img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
            card_images.append(img)
            print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
        else:
            print(f"卡片图片 {tile_path} 不存在")

    if not card_images:
        raise Exception("没有找到任何卡片图片")

except Exception as e:
    print(f"卡片图片加载失败: {e}")
    COLORS = [
        (255, 0, 0),  # 红
        (0, 255, 0),  # 绿
        (0, 0, 255),  # 蓝
        (255, 255, 0),  # 黄
        (128, 0, 128),  # 紫
        (255, 165, 0),  # 橙
        (0, 191, 255),  # 天蓝
    ]

# 尝试加载中文字体
try:
    # 尝试加载系统中文字体
    pygame.font.init()
    font_options = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC", "Microsoft YaHei"]
    font_available = None

    for font_name in font_options:
        if font_name in pygame.font.get_fonts():
            font_available = font_name
            break

    if font_available:
        print(f"找到中文字体: {font_available}")
    else:
        print("未找到系统中文字体，使用默认字体")
        font_available = pygame.font.get_default_font()

except Exception as e:
    print(f"字体初始化失败: {e}")
    font_available = pygame.font.get_default_font()


# 粒子效果类
class Particle:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.color = color
        self.radius = random.randint(2, 5)
        self.speed_x = random.uniform(-3, 3)
        self.speed_y = random.uniform(-5, -1)
        self.gravity = 0.1
        self.life = random.randint(20, 40)

    def update(self):
        self.x += self.speed_x
        self.y += self.speed_y
        self.speed_y += self.gravity
        self.life -= 1

    def draw(self, surface):
        alpha = int((self.life / 40) * 255)
        if alpha > 0:
            s = pygame.Surface((self.radius * 2, self.radius * 2), pygame.SRCALPHA)
            pygame.draw.circle(s, (*self.color, alpha), (self.radius, self.radius), self.radius)
            surface.blit(s, (int(self.x - self.radius), int(self.y - self.radius)))


# 得分增加动画类
class ScorePopup:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.value = "+1"
        self.font = pygame.font.SysFont(font_available, 30)
        self.color = (255, 215, 0)  # 金色
        self.life = 40
        self.speed_y = -1

    def update(self):
        self.y += self.speed_y
        self.life -= 1

    def draw(self, surface):
        alpha = int((self.life / 40) * 255)
        if alpha > 0:
            text = self.font.render(self.value, True, self.color)
            text.set_alpha(alpha)
            surface.blit(text, (self.x, self.y))


# 游戏状态类 - 重构游戏状态管理
class GameState:
    def __init__(self):
        self.reset()

    def reset(self):
        self.slots = []
        self.score = 0
        self.game_over = False
        self.game_won = False
        self.remove_card_count = 3
        self.shuffle_count = 3
        self.hint_count = 2
        self.start_time = time.time()
        self.last_hint_time = 0
        self.hint_active = False
        self.hint_positions = []

    def is_time_up(self):
        return time.time() - self.start_time > TIME_LIMIT

    def get_remaining_time(self):
        return max(0, TIME_LIMIT - (time.time() - self.start_time))

    def can_use_hint(self):
        return self.hint_count > 0 and time.time() - self.last_hint_time > 3

    def use_hint(self):
        if self.can_use_hint():
            self.hint_count -= 1
            self.last_hint_time = time.time()
            self.hint_active = True
            self.find_hint_positions()
            return True
        return False

    def find_hint_positions(self):
        # 寻找可以匹配的卡片位置
        self.hint_positions = []
        card_counts = {}

        # 检查卡槽中的卡片
        for card in self.slots:
            if card in card_counts:
                card_counts[card] += 1
            else:
                card_counts[card] = 1

        # 寻找需要的卡片类型
        needed_cards = [card for card, count in card_counts.items() if count < 3]

        # 如果卡槽中没有卡片或者所有卡片都已经有3个，则随机选择一个可点击的卡片
        if not needed_cards:
            for row in range(GRID_ROWS):
                for col in range(GRID_COLS):
                    if len(grid[row][col]) > 0:
                        self.hint_positions.append((row, col))
                        if len(self.hint_positions) >= 3:  # 最多提示3个位置
                            return
        else:
            # 寻找需要的卡片在网格中的位置
            for card_type in needed_cards:
                for row in range(GRID_ROWS):
                    for col in range(GRID_COLS):
                        if len(grid[row][col]) > 0 and grid[row][col][-1] == card_type:
                            self.hint_positions.append((row, col))
                            if len(self.hint_positions) >= 3:  # 最多提示3个位置
                                return


# 初始化游戏
def init_game():
    global grid, game_state, particles, score_popups  # 添加particles和score_popups到全局变量
    game_state = GameState()
    particles = []  # 初始化粒子列表
    score_popups = []  # 初始化得分动画列表

    # 初始化卡片堆
    grid = []
    for row in range(GRID_ROWS):
        grid_row = []
        for col in range(GRID_COLS):
            layers = random.randint(3, 5)
            max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
            stack = [random.randint(0, max_card_type) for _ in range(layers)]
            stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
            grid_row.append(stack)
        grid.append(grid_row)


def check_victory(grid):
    """检查是否胜利"""
    for row in grid:
        for stack in row:
            if len(stack) > 0:
                return False
    return len(game_state.slots) == 0


def remove_card():
    """移除槽位中最后一个卡片"""
    if game_state.remove_card_count > 0 and game_state.slots:
        game_state.slots.pop()
        game_state.remove_card_count -= 1


def shuffle_grid():
    """洗牌功能"""
    if game_state.shuffle_count > 0:
        all_cards = []
        for row in grid:
            for stack in row:
                all_cards.extend(stack)
                stack.clear()
        random.shuffle(all_cards)
        index = 0
        for row in grid:
            for stack in row:
                layers = random.randint(3, 5)
                stack.extend(all_cards[index:index + layers])
                index += layers
        game_state.shuffle_count -= 1


def get_hint():
    """使用提示功能"""
    return game_state.use_hint()


# 增加难度函数
def increase_difficulty():
    if game_state.score >= HARD_MODE_THRESHOLD:
        # 分数达到阈值后增加难度
        for row in grid:
            for stack in row:
                if stack and random.random() < 0.2:  # 20%概率增加层数
                    max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
                    stack.append(random.randint(0, max_card_type))


# 初始化游戏
init_game()

# 游戏主循环
clock = pygame.time.Clock()
running = True

while running:
    # 事件处理
    mouse_pos = pygame.mouse.get_pos()
    restart_button_hover = (
            RESTART_BUTTON_LEFT <= mouse_pos[0] <= RESTART_BUTTON_LEFT + RESTART_BUTTON_WIDTH and
            RESTART_BUTTON_TOP <= mouse_pos[1] <= RESTART_BUTTON_TOP + RESTART_BUTTON_HEIGHT
    )

    item1_button_hover = (
            ITEM_LEFT <= mouse_pos[0] <= ITEM_LEFT + ITEM_WIDTH and
            ITEM_TOP <= mouse_pos[1] <= ITEM_TOP + ITEM_HEIGHT
    )

    item2_button_hover = (
            ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= mouse_pos[0] <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and
            ITEM_TOP <= mouse_pos[1] <= ITEM_TOP + ITEM_HEIGHT
    )

    item3_button_hover = (
            ITEM_LEFT + 2 * (ITEM_WIDTH + ITEM_SPACING) <= mouse_pos[
        0] <= ITEM_LEFT + 3 * ITEM_WIDTH + 2 * ITEM_SPACING and
            ITEM_TOP <= mouse_pos[1] <= ITEM_TOP + ITEM_HEIGHT
    )

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if game_state.game_over and restart_button_hover:
                init_game()
            elif not game_state.game_over:
                x, y = event.pos
                # 检查是否点击道具按钮
                if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
                    remove_card()
                elif ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING <= x <= ITEM_LEFT + 2 * ITEM_WIDTH + ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
                    shuffle_grid()
                elif ITEM_LEFT + 2 * (
                        ITEM_WIDTH + ITEM_SPACING) <= x <= ITEM_LEFT + 3 * ITEM_WIDTH + 2 * ITEM_SPACING and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
                    get_hint()
                else:
                    # 计算点击位置
                    grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
                    grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
                    # 检查点击范围
                    if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
                        if len(grid[grid_row][grid_col]) > 0:
                            # 检查槽位是否已满
                            if len(game_state.slots) >= SLOT_COLS:
                                game_state.game_over = True
                                continue

                            # 取出顶层卡片
                            moving_card = grid[grid_row][grid_col].pop()
                            start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING)
                            start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) + (
                                len(grid[grid_row][grid_col])) * OVERLAP_OFFSET
                            target_x = SLOT_LEFT + len(game_state.slots) * (CARD_WIDTH + 5)
                            target_y = SLOT_TOP
                            card_moving = True
                            move_timer = 0

                            # 添加卡片到槽位
                            game_state.slots.append(moving_card)

                            # 检查是否有三张相同的卡片
                            last_card = game_state.slots[-1]
                            count = game_state.slots.count(last_card)
                            if count >= 3:
                                # 创建粒子效果
                                particle_color = COLORS[last_card] if not card_images else (
                                random.randint(200, 255), random.randint(200, 255), random.randint(200, 255))
                                for _ in range(30):
                                    particles.append(Particle(target_x + CARD_WIDTH // 2, target_y + CARD_HEIGHT // 2,
                                                              particle_color))

                                # 创建得分动画
                                score_popups.append(ScorePopup(target_x + CARD_WIDTH // 2 - 10, target_y - 30))

                                # 移除三张相同的卡片
                                game_state.slots = [card for card in game_state.slots if card != last_card]

                                # 增加分数
                                game_state.score += 1

                                # 检查难度是否需要增加
                                increase_difficulty()

    # 移动背景图
    bg_x -= BG_MOVE_SPEED
    if bg_x <= -SCREEN_WIDTH:
        bg_x = 0

    # 更新粒子效果
    for particle in particles[:]:
        particle.update()
        if particle.life <= 0:
            particles.remove(particle)

    # 更新得分动画
    for popup in score_popups[:]:
        popup.update()
        if popup.life <= 0:
            score_popups.remove(popup)

    # 检查提示状态
    if game_state.hint_active:
        if time.time() - game_state.last_hint_time > 3:
            game_state.hint_active = False

    # 检查时间限制
    if game_state.get_remaining_time() <= 0 and not game_state.game_over:
        game_state.game_over = True
        game_state.game_won = False

    # 绘制界面
    if background_img:
        screen.blit(background_img, (bg_x, 0))
        screen.blit(background_img, (bg_x + SCREEN_WIDTH, 0))
    else:
        screen.fill(BG_COLOR)

    # 绘制标题
    title_font = pygame.font.SysFont(font_available, 40)
    title_text = title_font.render("羊了个羊", True, (0, 0, 0))
    screen.blit(title_text, (SCREEN_WIDTH // 2 - title_text.get_width() // 2, 50))

    # 绘制时间条
    remaining_time = game_state.get_remaining_time()
    time_bar_width = int((remaining_time / TIME_LIMIT) * TIME_BAR_WIDTH)
    pygame.draw.rect(screen, (200, 200, 200),
                     (TIME_BAR_LEFT, TIME_BAR_TOP, TIME_BAR_WIDTH, TIME_BAR_HEIGHT),
                     border_radius=5)
    pygame.draw.rect(screen, TIME_BAR_COLOR,
                     (TIME_BAR_LEFT, TIME_BAR_TOP, time_bar_width, TIME_BAR_HEIGHT),
                     border_radius=5)

    time_font = pygame.font.SysFont(font_available, 20)
    time_text = time_font.render(f"剩余时间: {int(remaining_time)}s", True, TEXT_COLOR)
    screen.blit(time_text, (TIME_BAR_LEFT - time_text.get_width() - 10, TIME_BAR_TOP))

    # 绘制卡片堆，添加叠罗汉效果和鼠标悬停放大
    for row in range(GRID_ROWS):
        for col in range(GRID_COLS):
            x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
            y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
            stack = grid[row][col]
            for i, card_type in enumerate(stack):
                offset_y = i * OVERLAP_OFFSET
                card_x = x
                card_y = y + offset_y

                # 检查是否为提示位置
                is_hint = game_state.hint_active and (row, col) in game_state.hint_positions

                # 检查鼠标是否悬停在卡片上
                mouse_x, mouse_y = pygame.mouse.get_pos()
                is_hover = (
                        card_x <= mouse_x <= card_x + CARD_WIDTH
                        and card_y <= mouse_y <= card_y + CARD_HEIGHT
                )

                # 计算卡片大小和位置
                scale_factor = 1.2 if is_hover or is_hint else 1
                scaled_width = int(CARD_WIDTH * scale_factor)
                scaled_height = int(CARD_HEIGHT * scale_factor)
                draw_x = card_x - (scaled_width - CARD_WIDTH) // 2
                draw_y = card_y - (scaled_height - CARD_HEIGHT) // 2

                if card_images:
                    scaled_img = pygame.transform.scale(card_images[card_type], (scaled_width, scaled_height))
                    screen.blit(scaled_img, (draw_x, draw_y))
                else:
                    pygame.draw.rect(
                        screen,
                        COLORS[card_type],
                        (draw_x, draw_y, scaled_width, scaled_height)
                    )

                # 添加提示高亮
                if is_hint:
                    highlight_surf = pygame.Surface((scaled_width, scaled_height), pygame.SRCALPHA)
                    highlight_surf.fill((HINT_COLOR[0], HINT_COLOR[1], HINT_COLOR[2], 100))
                    screen.blit(highlight_surf, (draw_x, draw_y))

    # 绘制槽位背景
    if slot_bg_img:
        screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
    else:
        pygame.draw.rect(
            screen,
            (200, 200, 200),
            (SLOT_LEFT - 5, SLOT_TOP - 5, slot_width + 10, SLOT_HEIGHT + 10),
            border_radius=10
        )

    # 绘制槽位标题
    slot_font = pygame.font.SysFont(font_available, 24)
    slot_text = slot_font.render("卡槽", True, (0, 0, 0))
    screen.blit(slot_text, (SLOT_LEFT + slot_width // 2 - slot_text.get_width() // 2, SLOT_TOP - 30))

    # 绘制槽位中的卡片
    for i, card in enumerate(game_state.slots):
        x = SLOT_LEFT + i * (CARD_WIDTH + 5)
        if card_images:
            screen.blit(card_images[card], (x, SLOT_TOP))
        else:
            pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))

    # 绘制状态信息
    status_font = pygame.font.SysFont(font_available, 28)
    score_text = status_font.render(f"得分: {game_state.score}", True, TEXT_COLOR)
    screen.blit(score_text, (20, 20))

    # 绘制槽位容量提示
    capacity_text = status_font.render(f"已用: {len(game_state.slots)}/{SLOT_COLS}", True, CAPACITY_COLOR)
    screen.blit(capacity_text, (SCREEN_WIDTH - capacity_text.get_width() - 20, 20))

    # 绘制道具按钮
    # 移除道具按钮
    pygame.draw.rect(
        screen,
        ITEM_COLOR_1 if not item1_button_hover else (0, 168, 0),
        (ITEM_LEFT, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
        border_radius=5
    )
    # 洗牌道具按钮
    pygame.draw.rect(
        screen,
        ITEM_COLOR_2 if not item2_button_hover else (0, 0, 168),
        (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING, ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
        border_radius=5
    )
    # 提示道具按钮
    pygame.draw.rect(
        screen,
        ITEM_COLOR_3 if not item3_button_hover else (168, 0, 0),
        (ITEM_LEFT + 2 * (ITEM_WIDTH + ITEM_SPACING), ITEM_TOP, ITEM_WIDTH, ITEM_HEIGHT),
        border_radius=5
    )

    # 绘制道具按钮文字
    item_font = pygame.font.SysFont(font_available, 20)
    remove_text = item_font.render(f"移除 ×{game_state.remove_card_count}", True, ITEM_TEXT_COLOR)
    shuffle_text = item_font.render(f"洗牌 ×{game_state.shuffle_count}", True, ITEM_TEXT_COLOR)
    hint_text = item_font.render(f"提示 ×{game_state.hint_count}", True, ITEM_TEXT_COLOR)
    screen.blit(remove_text, (ITEM_LEFT + 5, ITEM_TOP + 10))
    screen.blit(shuffle_text, (ITEM_LEFT + ITEM_WIDTH + ITEM_SPACING + 5, ITEM_TOP + 10))
    screen.blit(hint_text, (ITEM_LEFT + 2 * (ITEM_WIDTH + ITEM_SPACING) + 5, ITEM_TOP + 10))

    # 绘制粒子效果
    for particle in particles:
        particle.draw(screen)

    # 绘制得分动画
    for popup in score_popups:
        popup.draw(screen)

    # 游戏结束时显示结果和重玩按钮
    if game_state.game_over:
        # 绘制半透明遮罩
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 128))
        screen.blit(overlay, (0, 0))

        # 绘制游戏结果
        result_font = pygame.font.SysFont(font_available, 50)
        result_text = result_font.render("恭喜你赢了!" if game_state.game_won else "游戏结束!",
                                         True, WIN_COLOR if game_state.game_won else LOSE_COLOR)
        screen.blit(result_text, (SCREEN_WIDTH // 2 - result_text.get_width() // 2, SCREEN_HEIGHT // 2 - 70))

        # 绘制最终得分
        final_score_font = pygame.font.SysFont(font_available, 36)
        final_score_text = final_score_font.render(f"最终得分: {game_state.score}", True, (255, 255, 255))
        screen.blit(final_score_text, (SCREEN_WIDTH // 2 - final_score_text.get_width() // 2, SCREEN_HEIGHT // 2 - 20))

        # 绘制重玩按钮
        pygame.draw.rect(
            screen,
            BUTTON_HOVER_COLOR if restart_button_hover else BUTTON_COLOR,
            (RESTART_BUTTON_LEFT, RESTART_BUTTON_TOP, RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT),
            border_radius=10
        )
        restart_text = pygame.font.SysFont(font_available, 36).render("再玩一次", True, BUTTON_TEXT_COLOR)
        screen.blit(
            restart_text,
            (
                RESTART_BUTTON_LEFT + (RESTART_BUTTON_WIDTH - restart_text.get_width()) // 2,
                RESTART_BUTTON_TOP + (RESTART_BUTTON_HEIGHT - restart_text.get_height()) // 2
            )
        )

    pygame.display.flip()
    clock.tick(60)

pygame.quit()




